//
//  BldPresView.m
//  AccuroScale
//
//  Created by Yongfeng Li on 6/16/14.
//  Copyright (c) 2014 Yongfeng Li. All rights reserved.
//

#import "BldPresView.h"
#import "UIView+Extension.h"
#define DefaultColor [UIColor colorWithRed:0.83 green:0.00 blue:0.40 alpha:1.00]
//meas arc

#define degreesToRadians(x) (M_PI*(x)/180.0) //把角度转换成PI的方式
#define PROGREESS_RADIUS 140 //圆直径
#define PROGRESS_LINE_WIDTH 8 //弧线的宽度

//pres column
#define _tMargin 24
#define _bMaring 12
#define _xEndPos 120
#define _xWidth 52

#define _xMargin 3
#define _yMargin 5

#define _minAngle -200 //-200
#define _maxAngle 20 //20


//#define _markWidth 150
//#define _markWidth 350
#define _hgtCtrl 185
//#define _hgtCtrl 385

static BOOL _bMeasEnd = NO;
static BOOL _bPadRing = NO;


@implementation ValuesNeedle {
    
}

- (id)initWithView:(UIView *)view {
  self = [super init];
  if (self != nil) {
    _view = view;
  }
  return self;
}

- (void) drawLayer:(CALayer*)layer inContext:(CGContextRef)ctx {
    //return;
    
	CGContextSaveGState(ctx);
	CATransform3D transform = layer.transform;
	layer.transform = CATransform3DIdentity;
	
  //CGFloat W = layer.frame.size.width;
  //CGFloat H = layer.frame.size.height;

  CGFloat yPos = layer.frame.origin.y;
    
  //CGContextSetBlendMode(ctx, kCGBlendModeScreen);
  CGContextSetStrokeColorWithColor(ctx, [UIColor orangeColor].CGColor);
  CGContextSetFillColorWithColor(ctx, self.fillcolor.CGColor);
	CGContextSetLineWidth(ctx, self.width);

  CGFloat xMarg = 27.5;//20;
  CGFloat yMarg = yPos+12;
  /*if(_bPadRing) {
    xMarg -= 4;
    yMarg += 10;
   }*/
	CGContextBeginPath(ctx);
  CGContextAddEllipseInRect(ctx, CGRectMake(xMarg, yMarg, 12, 8)); //椭圆
  CGContextDrawPath(ctx, kCGPathFillStroke); //kCGPathFillStroke. kCGPathStroke, 绘制填充
    
    //CGContextStrokePath(ctx);
    
	layer.transform = transform;
	CGContextRestoreGState(ctx);
    
  //test
  /*CGContextSaveGState(ctx);
  CATransform3D transform = layer.transform;
     
  layer.transform = CATransform3DIdentity;
     
  //CGContextSetFillColorWithColor(ctx, self.tintColor.CGColor);
  //CGContextSetStrokeColorWithColor(ctx, self.tintColor.CGColor);
  CGContextSetFillColorWithColor(ctx, [UIColor blackColor].CGColor);
  CGContextSetStrokeColorWithColor(ctx, [UIColor blackColor].CGColor);
  CGContextSetLineWidth(ctx, self.width);
     
  CGFloat centerX = layer.frame.size.width / 2.0;
  CGFloat centerY = layer.frame.size.height / 2.0;
  CGFloat ellipseRadius = self.width * 2.0;
  //CGContextFillEllipseInRect(ctx, CGRectMake(centerX - ellipseRadius, centerY - ellipseRadius, ellipseRadius * 2.0, ellipseRadius * 2.0));
  CGFloat endX = (1 + self.length) * centerX;
     
  CGContextBeginPath(ctx);
  CGContextMoveToPoint(ctx, 50, 30);
  CGContextAddLineToPoint(ctx, 55, 30);
  CGContextStrokePath(ctx);
   
  layer.transform = transform;
  CGContextRestoreGState(ctx);*/
    
  /* color pregress
  [CATransaction begin];
  [CATransaction setDisableActions:!animated];
  [CATransaction setAnimationTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn]];
  [CATransaction setAnimationDuration:MAIN_SCREEN_ANIMATION_TIME];
  _progressLayer.strokeEnd = percent/100.0;
  [CATransaction commit];
     
  _percent = percent;*/
}

- (void)dealloc {
    
}
@end

@implementation BldPresView {
    //BOOL _bMale;
    short _minBldPres;
    short _maxBldPres;
    
    short _nLastPres;
    
    short _nHpresVal;
    short _nLpresVal;
    short _nHrateVal;
    
    UIImageView* _ivBkgd;
    UIImageView* _ivMeas;
    
    BOOL _bDesHgt;
    CAShapeLayer* _trackLayer;
    CAGradientLayer* _gradientLayer;
    
    CALayer *_hPresLayer;
    ValuesNeedle* _needleHpres;
    
    CALayer *_lPresLayer;
    ValuesNeedle* _needleLpres;
    
    UILabel* _lblBldPres;
    UILabel* _lblRate;
    
    BOOL _bIsIpad;
    CGFloat _nPresCtrlHgt;
    CGFloat _nPresCtrlTop;
}

- (id)initWithFrame:(CGRect)frame
{
    _bIsIpad = NO;
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.backgroundColor = [UIColor clearColor];
        //self.backgroundColor = [UIColor whiteColor];
        [self initialize];
    }
    return self;
}

- (void)initialize {
    _bDesHgt = NO;
    
    _minBldPres = 0;
    _maxBldPres = 256;
    
    _nLastPres = 0;
    
    CGFloat W = self.frame.size.width;
    CGFloat H = self.frame.size.height;
    _bPadRing = H > 500;
    
    CGFloat yMarg = (H > _hgtCtrl)? _tMargin+10: _tMargin+5;
    //if(H > 500)
        //yMarg += 40;
    UIImage* iBkgd = [UIImage imageNamed:@"ic-hBldpre.png"];
    _ivMeas= [[UIImageView alloc] initWithImage:iBkgd];
    _ivMeas.frame = CGRectMake(W-(_bPadRing? 140: ((H < 267)?65:80)), yMarg, 32, 32);
    [self addSubview:_ivMeas];
    _ivMeas.hidden = YES;
    
    //iBkgd = [UIImage imageNamed:@"Ic-BldPres-Meas.png"];
    /*iBkgd = [UIImage imageNamed:bMale? @"Ic-BldPres-Male.png": @"Ic-BldPres-Meas.png"];
    _imgBkgd = [[UIImageView alloc] initWithImage:iBkgd];
    CGFloat xMarg = (W > 500)? 60: 10;
    yMarg = (W > 500)? ((H-360)/2-32): ((H-160)/2+16);
    _imgBkgd.frame = CGRectMake(xMarg, yMarg, (W > 500)?300:160, (W > 500)?300:160);
    [self addSubview:_imgBkgd];*/
    
    CGFloat xPos = W - ((H > 500)? 300: 150);
    CGFloat yPos = (H>_hgtCtrl)? 180: 90;
    CGFloat fCtrlWid = (H > 500)? (W-50): (W/2+50);
    CGFloat fCtrlHgt = (H > 500)? (H*4/5): (H*2/3);
    _trackLayer = [CAShapeLayer layer];//创建一个track shape layer
    _trackLayer.frame = CGRectMake(xPos, yPos, fCtrlWid, fCtrlHgt);//self.bounds;
    //_trackLayer.bounds = _trackLayer.frame;
    
    fCtrlWid = PROGREESS_RADIUS+70;
    fCtrlHgt = PROGREESS_RADIUS+70;
    if(H > 500) {
        fCtrlWid *= 1.8;
        fCtrlHgt *= 1.8;
    }
    _gradientLayer =  [CAGradientLayer layer];
    _gradientLayer.frame = CGRectMake(0, 0, fCtrlWid, fCtrlHgt);
    //_gradientLayer.backgroundColor = [UIColor lightGrayColor].CGColor;
    [_gradientLayer setMask:_trackLayer]; //用_trackLayer来截取渐变层
    [self.layer addSublayer:_gradientLayer];
    //[self drawGradientArcColor];
    
    //blood pres
    CGFloat yOff = (H>_hgtCtrl)? yPos-115:yPos-65;
    if(H > 500) {
        xPos += 50;
    }
    else if(H < 267) {
        yOff -= 20;
    }
    _lblBldPres = [[UILabel alloc] initWithFrame:CGRectMake(xPos-(_bPadRing?40:-30) , yOff, _bPadRing?120:80, _bPadRing? 150: 100)];
    //_lblBldPres.font = [UIFont fontWithName:@"Calibri-Bold" size:15.0];
    _lblBldPres.font = [UIFont boldSystemFontOfSize:(_bPadRing? 30.0f:20.0f)];
    _lblBldPres.textColor = [UIColor blackColor]; //blackColor
    _lblBldPres.backgroundColor = [UIColor clearColor];
    _lblBldPres.textAlignment = NSTextAlignmentCenter;
    _lblBldPres.lineBreakMode = NSLineBreakByWordWrapping;
    _lblBldPres.numberOfLines = 0;
    _lblBldPres.text = @"------";
    [self addSubview:_lblBldPres];
    //_lblBldPres.backgroundColor = [UIColor lightGrayColor];
    
    //heart rate
    _lblRate= [[UILabel alloc] initWithFrame:CGRectMake(xPos-(_bPadRing?110:20), yOff+(_bPadRing? 150:100), (_bPadRing?270:180), 25)];
    //_lblRate.font = [UIFont fontWithName:@"Calibri-Bold" size:15.0];
    _lblRate.font = [UIFont boldSystemFontOfSize:(_bPadRing? 30.0f:20.0f)];
    _lblRate.textColor = [UIColor blackColor];//[UIColor grayColor];
    _lblRate.backgroundColor = [UIColor clearColor];
    _lblRate.textAlignment = NSTextAlignmentCenter;
    _lblRate.text = @"......";
    [self addSubview:_lblRate];
    //_lblRate.backgroundColor = [UIColor lightGrayColor];
    
    
    xPos = PROGRESS_LINE_WIDTH + 5.27;
    yPos -= 36;//H/2-30;
    fCtrlWid = PROGREESS_RADIUS+32;
    fCtrlHgt = 32;
    if(H <= _hgtCtrl)
        yPos += PROGREESS_RADIUS/2 - PROGRESS_LINE_WIDTH - 2;
    
    if(H > 500) {
        //xPos += 0.2;
        yPos += 38;
        fCtrlWid *= 1.582;//PROGREESS_RADIUS;
    }
    //h pres needle
  /*_needleHpres = [[ValuesNeedle alloc] initWithView:self];
	_needleHpres.tintColor = [UIColor orangeColor];
	_needleHpres.width = 2.0;
	_needleHpres.fillcolor = [UIColor colorWithRed:0.5 green:0.1 blue:0.1 alpha:0.36];*/
    
    
  CGFloat yy = (H>_hgtCtrl)?yPos+20: yPos;
  _hPresLayer = [CALayer layer];
	_hPresLayer.bounds = CGRectMake(xPos, yy, fCtrlWid, fCtrlHgt);
  _hPresLayer.frame = CGRectMake(xPos, yy, fCtrlWid, fCtrlHgt);
	//_hPresLayer.position = CGPointMake(xPos, yPos);//xPos, yPos);
	_hPresLayer.needsDisplayOnBoundsChange = YES;
  //_hPresLayer.delegate = _needleHpres;
	
    //_hPresLayer.backgroundColor = [UIColor colorWithRed:0.5 green:0.5 blue:0.5 alpha:.5].CGColor;
	[self.layer addSublayer:_hPresLayer];

    
  //l pres needle
  /*_needleLpres = [[ValuesNeedle alloc] initWithView:self];
	_needleLpres.tintColor = [UIColor orangeColor];
	_needleLpres.width = 2.0;
	_needleLpres.fillcolor = [UIColor colorWithRed:0.1 green:0.5 blue:0.5 alpha:0.36];*/
    
  //xPos -= 20;
  _lPresLayer = [CALayer layer];
	_lPresLayer.bounds = CGRectMake(xPos, yy, fCtrlWid, fCtrlHgt);
  _lPresLayer.frame = CGRectMake(xPos, yy, fCtrlWid, fCtrlHgt);
	//_lPresLayer.position = CGPointMake(xPos, PROGREESS_RADIUS+55);
	_lPresLayer.needsDisplayOnBoundsChange = YES;
	//_lPresLayer.delegate = _needleLpres;
	
  //_lPresLayer.backgroundColor = [UIColor colorWithRed:0.5 green:0.5 blue:0.5 alpha:.5].CGColor;
	[self.layer addSublayer:_lPresLayer];
	
  _gradientLayer.hidden = YES;
  _hPresLayer.hidden = YES;
  _lPresLayer.hidden = YES;
  _lblBldPres.hidden = YES;
  _lblRate.hidden = YES;
}

- (void) setMeasBodySex: (BOOL) bMale
{
    UIImage* iBkgd = [UIImage imageNamed:bMale? @"Ic-BldPres-Male.png": @"Ic-BldPres-Meas.png"];
    [_ivBkgd setImage:iBkgd];
    
}

- (void) drawGradientArcColor
{
     CGFloat H = self.frame.size.height;
    
    _trackLayer.fillColor = [[UIColor clearColor] CGColor];
    _trackLayer.strokeColor = [[UIColor blueColor] CGColor];//指定path的渲染颜色
    _trackLayer.opacity = 0.75; //背景同学你就甘心做背景吧，不要太明显了，透明度小一点
    _trackLayer.lineCap = kCALineCapRound;//指定线的边缘是圆的
    _trackLayer.lineWidth = PROGRESS_LINE_WIDTH;//线的宽度
    
    CGFloat xPos = (H>500)? 100: 50;
    CGFloat yPos = (H>_hgtCtrl)? 0: 40;
    CGFloat rSize = (PROGREESS_RADIUS-PROGRESS_LINE_WIDTH) / 2.0;
    if(H > 500) {
        //xPos -= 30;
        yPos += 40;
        rSize *= 1.75;
    }
    UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(xPos, yPos) radius:rSize
                        startAngle:degreesToRadians(_minAngle) endAngle:degreesToRadians(_maxAngle) clockwise:YES];//上面说明过了用来构建圆形
    //UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(xPos, yPos) radius:rSize
                                                    //startAngle:degreesToRadians(0) endAngle:degreesToRadians(350) clockwise:YES];
    _trackLayer.path =[path CGPath]; //把path传递給layer，然后layer会处理相应的渲染，整个逻辑和CoreGraph是一致的。
    //_trackLayer.backgroundColor = [UIColor lightGrayColor].CGColor;
    
    [_gradientLayer setColors:[NSArray arrayWithObjects:(id)[[UIColor blueColor] CGColor], (id)[[UIColor greenColor] CGColor],
                               (id)[[UIColor redColor] CGColor], nil]];
    //[_gradientLayer setLocations:@[@0.5,@0.9,@1 ]];
    
    [_gradientLayer setStartPoint:CGPointMake(0.10, 1.0)];
    [_gradientLayer setEndPoint:CGPointMake(0.65, 1.0)];
}


- (void) drawRuler:(CGContextRef)ctx xpos:(CGFloat)xPos ypos:(CGFloat)yPos ctrlHgt:(CGFloat)rtHgt scrHgt:(CGFloat)fHgt
{
    //return;
    NSInteger majorTickInterval = 5;
    //CGFloat currentHeight = 100;
    CGFloat currentHeight = rtHgt;//_bIsIpad?(fHgt-_tMargin-_bMaring-142):(fHgt-_tMargin-_bMaring+3); //_hgtCtrl;
    int leftEdgeForTicks = xPos;
    //int topEdgeForTicks = yPos;
    int majorTickLength = 15;
    int minorTickLength = 10;
    
    NSInteger minorTickCounter = majorTickInterval;
    NSInteger totalNumberOfTicks = 50;//totalTravelRangeInMicrons / minorTickSpacingInMicrons;
    
    if(fHgt > 500) {
        //currentHeight = 140;
        totalNumberOfTicks = 70;
    }
    
    CGFloat minorTickSpacingInPixels = currentHeight / totalNumberOfTicks - 0.05;//(CGFloat)totalNumberOfTicks;
    //if(fHgt <= _hgtCtrl)
        //minorTickSpacingInPixels -= 1.75;   
    
    CGContextSetStrokeColorWithColor(ctx, [[UIColor blackColor] CGColor]);
    //CGContextSetStrokeColorWithColor(ctx, [[UIColor whiteColor] CGColor]);
    UIFont *bFont = Bold([UIScreen mainScreen].bounds.size.height / 48);
    for (NSInteger currentTickNumber = 0; currentTickNumber < totalNumberOfTicks; currentTickNumber++) {
        //CGFloat yyPos = yPos+round(currentTickNumber * minorTickSpacingInPixels) + 0.5;
        CGFloat yyPos = yPos+(currentTickNumber * minorTickSpacingInPixels) + 0.5;
        CGContextMoveToPoint(ctx, leftEdgeForTicks + 0.5, yyPos);
        
        minorTickCounter++;
        if (minorTickCounter >= majorTickInterval) {
            CGContextAddLineToPoint(ctx, round(leftEdgeForTicks + majorTickLength) + 3.5, yyPos);
            minorTickCounter = 0;
        }
        else {
            CGContextAddLineToPoint(ctx, round(leftEdgeForTicks + minorTickLength) + 0.5, yyPos);
        }
        if(currentTickNumber == 0) {
            NSString* sText = @"256 mmHG";
            //[sText drawAtPoint: CGPointMake(leftEdgeForTicks-75, yyPos-8) withFont:[UIFont systemFontOfSize:14]];
            NSDictionary *attrsDic = @{NSFontAttributeName: bFont, NSForegroundColorAttributeName: [UIColor colorWithRed:0.83 green:0.00 blue:0.40 alpha:1.00]};
            [sText drawAtPoint: CGPointMake(leftEdgeForTicks-80, yyPos-8) withAttributes:attrsDic];
        }
        else if(currentTickNumber == totalNumberOfTicks/2) {
            NSString* sText = @"128 mmHG";
            //[sText drawAtPoint: CGPointMake(leftEdgeForTicks-32, yyPos-9) withFont:[UIFont systemFontOfSize:14]];
            //NSDictionary *attrsDic = [NSDictionary dictionaryWithObjectsAndKeys: [UIFont systemFontOfSize:14], NSFontAttributeName,
            //                          [NSNumber numberWithFloat:1.0], NSBaselineOffsetAttributeName, nil];
            NSDictionary *attrsDic = @{NSFontAttributeName: bFont, NSForegroundColorAttributeName: [UIColor colorWithRed:0.83 green:0.00 blue:0.40 alpha:1.00]};
            [sText drawAtPoint: CGPointMake(leftEdgeForTicks-80, yyPos-9) withAttributes:attrsDic];
        }
        else if(currentTickNumber == totalNumberOfTicks-1) {
            NSString* sText = @"0 mmHG";
            //[sText drawAtPoint: CGPointMake(leftEdgeForTicks-20, yyPos-2) withFont:[UIFont systemFontOfSize:14]];
            //NSDictionary *attrsDic = [NSDictionary dictionaryWithObjectsAndKeys: [UIFont systemFontOfSize:14], NSFontAttributeName,
            //                          [NSNumber numberWithFloat:1.0], NSBaselineOffsetAttributeName, nil];
             NSDictionary *attrsDic = @{NSFontAttributeName: bFont, NSForegroundColorAttributeName: [UIColor colorWithRed:0.83 green:0.00 blue:0.40 alpha:1.00]};
            [sText drawAtPoint: CGPointMake(leftEdgeForTicks-65, yyPos-2) withAttributes:attrsDic];
        }
        NSString* sText = @"0";
        NSDictionary *attrsDic = @{NSFontAttributeName: [UIFont systemFontOfSize:0.0], NSForegroundColorAttributeName: [UIColor blackColor]};
        [sText drawAtPoint: CGPointMake(leftEdgeForTicks-65, yyPos-2) withAttributes:attrsDic];
    }

    //zero line
    CGContextMoveToPoint(ctx, leftEdgeForTicks + 0.5, (yPos+totalNumberOfTicks * minorTickSpacingInPixels + 0.45));
    CGContextAddLineToPoint(ctx, round(leftEdgeForTicks + majorTickLength) + 3.5, (yPos+totalNumberOfTicks * minorTickSpacingInPixels + 0.45));
    
    CGContextStrokePath(ctx);
}

- (void) drawRect:(CGRect)rect
{
    CGFloat W = self.frame.size.width;
    CGFloat H = self.frame.size.height;
    //CGFloat hgtCtrl =  H - _tMargin - _bMaring - _yMargin * 2;
    BOOL bIpad = W > 700;
    _bIsIpad = bIpad;
    
    if(H > 500) {
        H -= 12;
    }
    
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    
    if(_bMeasEnd) {
        //CGFloat fCalHgt = H;
        CGContextClearRect(ctx, rect);
        //if(H > 500) {
            //fCalHgt = 372;
        //}
        CGFloat HGT = H - _tMargin - _bMaring - _yMargin * 2;
        CGFloat fPos1 = _nHpresVal * HGT / _maxBldPres;
        CGFloat fPos2 = _nLpresVal * HGT / _maxBldPres;
        CGFloat fBase = H - _bMaring - _yMargin;
        CGFloat yPos = fBase -fPos1;
        CGFloat fHgt = fPos1 - fPos2;
        
        
        //CGFloat xPos = W - _xEndPos + _xMargin;
        CGFloat xPos = _xEndPos +_xMargin;
        if(bIpad)
            xPos = xPos * 2.0 - 3;
        
        CGFloat fWidth = _xWidth - _xMargin * 2;
        
        
        /*CGFloat fHgt = _nPresCtrlHgt; //fCalHgt - _tMargin - _bMaring - _yMargin * 2;
        CGFloat yPos = fCalHgt - _bMaring - _yMargin - _nHpresVal * fHgt / _maxBldPres;
        fHgt = (_nHpresVal - _nLpresVal) * fHgt / _maxBldPres;*/
        CGRect rt = CGRectMake(xPos, yPos, fWidth, fHgt);
        //rt.size.height += 4;
        
        /*CGContextSetRGBFillColor(ctx, 1.0, 0.15, 0.01, 0.96);
        CGContextFillRect(ctx, rt);
        CGContextStrokePath(ctx);*/
        
//        CGContextSetRGBFillColor(ctx, 1.0, 0.15, 0.01, 0.96);
         CGContextSetRGBFillColor(ctx, 0.84, 0.0, 0.40, 0.96);
        CGContextFillRect(ctx, rt);
        CGContextStrokePath(ctx);
        
        _bMeasEnd = NO;
        
        return;
    }
    
    //set new val
    //if(rect.size.height < hgtCtrl) { //update
    if(rect.size.height < _nPresCtrlHgt) { //update
        if(_bDesHgt) {
            //rect.origin.y -= 2;
            //rect.size.height += 3;
            CGContextClearRect(ctx, rect);
        }
        else {
            /*CGFloat fDrawBott = rect.origin.y + rect.size.height;
            CGFloat fCtrlBott = _nPresCtrlTop + _nPresCtrlHgt;
            if(fDrawBott < _nPresCtrlTop + fCtrlBott)
                rect.size.height = rect.size.height + 100;*/
//            CGContextSetRGBFillColor(ctx, 0.2, 0.5, 0.9, 0.75);
            
            CGContextSetRGBFillColor(ctx, 0.84, 0.0, 0.40, 0.96);
            
            CGContextFillRect(ctx, rect);
            CGContextStrokePath(ctx);
        }
    }
    else { //ini clear
        CGContextSetRGBStrokeColor(ctx, 0.0, 0.0, 0.0, 1.0);
        CGContextSetLineWidth(ctx, 2.75);
        //CGRect rt = CGRectMake(W-_xEndPos, _tMargin, _xWidth, (W>500)?(H-_tMargin-_bMaring-142):(H-_tMargin-_bMaring+3));
        CGRect rt = CGRectMake(_xEndPos * (bIpad?2:1), _tMargin, _xWidth, bIpad?(H-_tMargin-_bMaring-2):(H-_tMargin-_bMaring-10));
        CGFloat rd = 5.0;
        
        CGFloat minx = CGRectGetMinX(rt), midx = CGRectGetMidX(rt), maxx = CGRectGetMaxX(rt);
        CGFloat miny = CGRectGetMinY(rt), midy = CGRectGetMidY(rt), maxy = CGRectGetMaxY(rt);
        
        //drae rect
        CGContextMoveToPoint(ctx, minx, midy);
        // Add an arc through 2 to 3
        CGContextAddArcToPoint(ctx, minx, miny, midx, miny, rd);
        // Add an arc through 4 to 5
        CGContextAddArcToPoint(ctx, maxx, miny, maxx, midy, rd);
        // Add an arc through 6 to 7
        CGContextAddArcToPoint(ctx, maxx, maxy, midx, maxy, rd);
        // Add an arc through 8 to 9
        CGContextAddArcToPoint(ctx, minx, maxy, minx, midy, rd);
        // Close the path
        CGContextClosePath(ctx);
        // Fill & stroke the path
        CGContextDrawPath(ctx, kCGPathStroke);//kCGPathFillStroke); kCGPathEOFill, not good
        //CGContextDrawPath(ctx, kCGPathEOFillStroke);
        
        _nPresCtrlHgt = rt.size.height;
        _nPresCtrlTop = rt.origin.y;
        CGContextSetLineWidth(ctx, 1.0);
        [self drawRuler:ctx xpos:_xEndPos*(bIpad?2:1)-_xWidth-_xMargin + _xWidth/2.0 ypos:_tMargin+2 ctrlHgt:rt.size.height scrHgt:H]; //hgt:H-_tMargin-_bMaring-_yMargin*2
    }
    
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/


- (void) startMeas
{
    _bDesHgt = YES;
    _bMeasEnd = NO;
    [self resetMeasData];
    _ivMeas.alpha = 1.0;
    
    //clear view on columm
    /*CGFloat W = self.frame.size.width;
    CGFloat H = self.frame.size.height;
     
    CGFloat xPos = W-_xEndPos +_xMargin;
    CGFloat yPos = _tMargin + _yMargin;
    CGFloat fWidth = _xWidth - _xMargin * 2;
    CGFloat fHgt = H - _tMargin - _bMaring - _yMargin * 2;
    CGRect rt = CGRectMake(xPos, yPos, fWidth, fHgt);
    [self setNeedsDisplayInRect:rt];*/
    [self setNeedsDisplay];
}

- (void) setPresVal:(short)nPres
{
    CGFloat fAlpha = _ivMeas.alpha;
    fAlpha -= 0.3;
    if(fAlpha < 0.3)
        fAlpha = 1.0;
    _ivMeas.alpha = fAlpha;
    
    
    if(nPres == _nLastPres)
        return;
    //CGFloat W = self.frame.size.width;
    //CGFloat H = self.frame.size.height;
    BOOL bIpad = _bIsIpad;//W > 700;
    //if(H > 500)
        //H = 372;
    
    //CGFloat HGT = H - _tMargin - _bMaring - _yMargin * 2;
    CGFloat HGT = _nPresCtrlHgt;
    
    CGFloat fPos1 = _nLastPres * HGT / _maxBldPres;
    CGFloat fPos2 = nPres * HGT / _maxBldPres;
    
    //CGFloat fBase = H - _bMaring - _yMargin;
    CGFloat fBase = _nPresCtrlHgt + _nPresCtrlTop;
    //if(H > 500)
        //fBase -= 120;
    CGFloat fStart = fBase -fPos2;
    CGFloat fHgt = fPos2 - fPos1;
    
    _bDesHgt = nPres < _nLastPres;
    if(_bDesHgt) {
        fStart = fBase - fPos1 - 0.1;
        fHgt = fPos1 - fPos2 + 0.2;
    }
    else {
        if(_nLastPres == 0)
            fHgt -= 2;
        else
            fHgt += 2;
    }
    
    //BOOL bOutDrawing = fStart >= fBase || fStart <= (_tMargin+_yMargin);
    BOOL bOutDrawing = fStart >= fBase || fStart <= _nPresCtrlTop;
    if(_bDesHgt && !bOutDrawing)
        bOutDrawing = (fStart+fHgt) >= fBase;
    if(bOutDrawing)
        return;
    
    CGFloat xPos = _xEndPos +_xMargin;
    if(bIpad)
        xPos = xPos * 2.0 - 3;
    //CGRect rt = CGRectMake(W-_xEndPos +_xMargin, fStart, _xWidth-_xMargin*2, fHgt);
    CGRect rt = CGRectMake(xPos, fStart, _xWidth-_xMargin*2, fHgt);
    
    //rt.size.height += 4;
    [self setNeedsDisplayInRect:rt];
    
    _nLastPres = nPres;
}

- (void) setBldPresNeedle:(short) nPres hPres:(BOOL)bHpres
{
    //CGFloat H = self.frame.size.height;
    
    CGFloat fDelta = _maxBldPres - _minBldPres;
    if(bHpres) {
        CGFloat angle = degreesToRadians(_maxAngle - _minAngle) * (nPres -_minBldPres) / fDelta - degreesToRadians(_maxAngle);
        _hPresLayer.transform = CATransform3DMakeRotation(angle, 0, 0, 1);
    }
    else {
        CGFloat angle = degreesToRadians(_maxAngle - _minAngle) * (nPres -_minBldPres) / fDelta - degreesToRadians(_maxAngle);
        _lPresLayer.transform = CATransform3DMakeRotation(angle, 0, 0, 1);
    }
}

- (void) setBledMeasData:(short) nHpres lPres:(short)nLpres hRate:(short)nHrate;
{
    _nLastPres = 0;
    _ivMeas.alpha = 1.0;
    
    _nHpresVal = nHpres;
    _nLpresVal = nLpres;
    _nHrateVal = nHrate;

    [self setBldPresNeedle:_nHpresVal hPres:YES];
    [self setBldPresNeedle:_nLpresVal hPres:NO];
    
    _lblBldPres.text = [NSString stringWithFormat:@"%d\nmmHg ~ \n %d", _nHpresVal, _nLpresVal];
    //_lblRate.text = [NSString stringWithFormat:@"%@: %d bpm", NSLocalizedString(@"hRate", nil), _nHrateVal];
    _lblRate.text = [NSString stringWithFormat:@"%@: %d bpm", @"HR", _nHrateVal];
    
    _bMeasEnd = YES;
    [self setBlelPresRngView];
}

- (void) setBlelPresRngView
{
    //CGFloat W = self.frame.size.width;
    //CGFloat H = self.frame.size.height;
    //if(H > 500) {
        //H = 340;
    //}
    
    
    CGFloat xPos = _xEndPos +_xMargin;
    if(_bIsIpad)
        xPos = xPos * 2.0 - 3;
    
    //CGFloat yPos = _tMargin + _yMargin;
    CGFloat yPos = _nPresCtrlTop + 2;
    CGFloat fWidth = _xWidth - _xMargin * 2;
    //CGFloat fHgt = H - _tMargin - _bMaring - _yMargin * 2;
    CGFloat fHgt = _nPresCtrlHgt - 4;
   
    CGRect rt = CGRectMake(xPos, yPos, fWidth, fHgt);
    
    //rt.size.height += 4;
    [self setNeedsDisplayInRect:rt];
}

- (void) resetMeasData
{
    _nLastPres = 0;
    _ivBkgd.hidden = YES;
    _ivMeas.hidden = NO;
    _ivMeas.alpha = 0.0;
    
    _gradientLayer.hidden = NO;
    _hPresLayer.hidden = NO;
    _lPresLayer.hidden = NO;
    _lblBldPres.hidden = NO;
    _lblRate.hidden = NO;
    
    //[self drawGradientArcColor];
    //_hPresLayer.position = CGPointMake(PROGREESS_RADIUS+12, PROGREESS_RADIUS+55);
    
    //[_hPresLayer setNeedsDisplay];
    //[_lPresLayer setNeedsDisplay];
    //[self setBldPresNeedle:_maxBldPres hPres:YES];
    //[self setBldPresNeedle:_minBldPres hPres:NO];
    
    _lblBldPres.text = @"------";
    _lblRate.text = @"......";
}

- (void) closeDevice
{
    _nLastPres = 0;
    _ivBkgd.hidden = NO;
    _ivMeas.hidden = YES;
    
    _hPresLayer.hidden = YES;
    _lPresLayer.hidden = YES;
    _lblBldPres.hidden = YES;
    _lblRate.hidden = YES;
    
    _gradientLayer.hidden = YES;
    
    [self setNeedsDisplay];
}

@end
